package com.work.shart.common.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.work.shart.common.exception.ExceptionEnum;
import com.work.shart.common.result.ResultVo;

import java.util.Date;

/**
 * jwt工具类
 * @author cong
 */
public class JwtTokenUtil {

    //定义token返回头部
    public static final String AUTH_HEADER_KEY = "Authorization";


    //token前缀
    public static final String TOKEN_PREFIX = "Bearer ";


    //签名密钥
    public static final String KEY = "q3t6w9z$C&F)J@NcQfTjWnZr4u7x";

    //有效期默认为 2hour
    public static final Long EXPIRATION_TIME = 1000L * 60 * 60 * 2;


    /**
     * 创建TOKEN
     *
     * @param content
     * @return
     */
    public static String createToken(String content) {
        return TOKEN_PREFIX + JWT.create()
                .withSubject(content)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(Algorithm.HMAC512(KEY));
    }


    /**
     * 验证token
     *
     * @param token
     */
    public static ResultVo verifyToken(String token) {
        try {
            return ResultVo.builder()
                    .code(200)
                    .data(JWT.require(Algorithm.HMAC512(KEY))
                            .build()
                            .verify(token.replace(TOKEN_PREFIX, ""))
                            .getSubject())
                    .build();
        } catch (TokenExpiredException e) {
            return ResultVo.builder()
                    .code(ExceptionEnum.TOKEN_INVALID.getCode())
                    .msg(ExceptionEnum.TOKEN_INVALID.getMsg())
                    .build();
        } catch (JWTVerificationException e) {
            return ResultVo.builder()
                    .code(ExceptionEnum.TOKEN_ERROR.getCode())
                    .msg(ExceptionEnum.TOKEN_ERROR.getMsg())
                    .build();

        }
    }

}
